package app.controllers.product;

import app.Const;
import app.models.basic.Dict;
import app.models.product.Brand;
import app.models.sys.User;
import com.google.common.base.Strings;
import com.jfinal.aop.Before;
import com.jfinal.ext.interceptor.GET;
import com.jfinal.ext.interceptor.POST;
import goja.mvc.Controller;
import goja.rapid.datatables.DTCriterias;
import goja.rapid.db.DaoKit;
import goja.security.shiro.AppUser;
import goja.security.shiro.Securitys;
import org.joda.time.DateTime;

import java.util.List;

/**
 * <p>
 * 产品品牌管理
 * </p>
 *
 * @author liuhui
 * @version 1.0
 * @since JDK 1.6
 */
public class BrandController extends Controller {

    @Before(GET.class)
    public void index(){
    }

    /**
     * 列表访问
     */
    @Before(GET.class)
    public void dtlist(){
        final DTCriterias criterias = getCriterias();
        renderDataTables(criterias,Brand.class);
    }

    @Before(GET.class)
    public void create() {
        Brand brand = new Brand();
        setAttr(Const.ACTION_ATTR, Const.CREATE_ACTION);
        List<Dict> datatypes = Dict.dao.dataTypes();
        setAttr("datatypes", datatypes);
        setAttr("brand",brand);
        render("item.ftl");
    }

    @Before(GET.class)
    public void edit() {
        String id = getPara(0, "0");
        Brand brand = Brand.dao.findById(id);
        setAttr(Const.ACTION_ATTR, Const.EDIT_ACTION);
        setAttr("brand",brand);
        render("item.ftl");
    }

    @Before(POST.class)
    public void save() {
        AppUser<User> loginUser = Securitys.getLogin();
        Brand brand = getModel(Brand.class,"brand");
        if (!Strings.isNullOrEmpty(getPara("pic_attachment"))) {
            brand.set("logo", getPara("pic_attachment_url"));
            brand.set("logo_attachment", getPara("pic_attachment"));
        }
        if (DaoKit.isNew(brand)) {
            brand.set(Const.FIELD_CREATE_TIME, DateTime.now());
            brand.save();
        } else {
            brand.update();
        }
        redirect("/product/brand");
    }

    public void delete(){
        int id = getParaToInt(0, 0);
        boolean status = Brand.dao.deleteById(id);
        if(status){
            renderAjaxSuccess();
        }else {
            renderAjaxFailure();
        }
    }

}
